<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 * @version    $Id: PhotoController.php 2011-03-09 08:45:41Z idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Vote
 * @copyright  Copyright KEENONWEB LLC
 * @license    http://www.keenonweb.com/
 */

class Vote_PhotoController extends Core_Controller_Action_Standard {
	public function init() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'view' )->isValid ())
			return;
		
		$id = $this->_getParam ( 'id', $this->_getParam ( 'challenge_id', 0 ) );
		if (! $id) {
			return;
		}
		
		if (! Engine_Api::_ ()->core ()->hasSubject ()) {
			$subject = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' )->find ( $id )->current ();
			if ($subject && $subject->getIdentity ()) {
				Engine_Api::_ ()->core ()->setSubject ( $subject );
			}
		}
	}
	
	public function browseAction() {
		$this->_forward ( 'index' );
	}
	
	public function indexAction() {
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_photo', array (), 'vote_main_photo_index' );
		
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'core' );
		
		$this->view->params = $params = array ('type' => 'photo', 'keyword' => $this->_getParam ( 'keyword', '' ), 'tag' => $this->_getParam ( 'tag', '' ), 'page' => $this->_getParam ( 'page', 1 ), 'ipp' => $settings->getSetting ( 'vote.page.count', 8 ), 'category' => $this->_getParam ( 'category', $this->_getParam ( 'category_id', 0 ) ), 'sort' => $this->_getParam ( 'sort', $this->_getParam ( 'orderby', '' ) ), 'has_photo' => $this->_getParam ( 'has_photo', 0 ), 'period' => $this->_getParam ( 'period', '' ), 'show' => $this->_getParam ( 'show', '' ), 'approved' => 1 );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$this->view->paginator = $paginator = $table->getPaginator ( $params );
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->can_create = Engine_Api::_ ()->vote ()->isAllowedCreation ();
		
		$this->view->form = $form = new Vote_Form_Photo_Search ();
		$form->setAction ( $this->view->url ( array ('controller' => 'photo', 'action' => 'index' ), 'vote_general', true ) );
		$form->populate ( $params );
		
		$values = array ('type' => 'photo', 'approved' => 1 );
		$this->view->tags = Engine_Api::_ ()->vote ()->getTags ( $values );
		
		$ids = array ();
		foreach ( $paginator as $voting ) {
			$ids [] = $voting->getIdentity ();
		}
		
		if (empty ( $ids )) {
			return;
		}
		
		$cnt = count ( $ids );
		$limit = ( int ) ($cnt * 16);
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$select = $table->select ()->where ( 'challenge_id IN (?)', $ids )->limit ( $limit );
		
		$data = $table->fetchAll ( $select );
		$participants = array ();
		
		foreach ( $data as $row ) {
			$challenge_id = $row->challenge_id;
			if (empty ( $participants [$challenge_id] )) {
				$participants [$challenge_id] = array ();
			}
			$participants [$challenge_id] [] = $row;
		}
		
		$this->view->participants = $participants;
	}
	
	public function manageAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'edit' )->isValid ())
			return;
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_photo', array (), 'vote_main_photo_manage' );
		
		$settings = Engine_Api::_ ()->getApi ( 'settings', 'core' );
		
		$this->view->params = $params = array ('type' => 'photo', 'keyword' => $this->_getParam ( 'keyword', '' ), 'tag' => $this->_getParam ( 'tag', '' ), 'page' => $this->_getParam ( 'page', 1 ), 'ipp' => $settings->getSetting ( 'vote.page.count', 8 ), 'category' => $this->_getParam ( 'category', $this->_getParam ( 'category_id', 0 ) ), 'sort' => $this->_getParam ( 'sort', $this->_getParam ( 'orderby', '' ) ), 'has_photo' => $this->_getParam ( 'has_photo', 0 ), 'period' => $this->_getParam ( 'period', '' ), 'user_id' => Engine_Api::_ ()->user ()->getViewer ()->getIdentity () );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$this->view->paginator = $paginator = $table->getPaginator ( $params );
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->can_create = Engine_Api::_ ()->vote ()->isAllowedCreation ();
		
		$this->view->form = $form = new Vote_Form_Photo_Search ();
		$form->setAction ( $this->view->url ( array ('controller' => 'photo', 'action' => 'manage' ), 'vote_general', true ) );
		$form->removeElement ( 'show' );
		$form->populate ( $params );
	}
	
	public function createAction() {
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'create' )->isValid ())
			return;
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_photo', array (), 'vote_main_photo_create' );
		
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->form = $form = new Vote_Form_Create ();
		
		$options = Engine_Api::_ ()->vote ()->getCategoryOptions ( 'photo' );
		if (! empty ( $options )) {
			$form->category_id->setMultiOptions ( $options );
		} else {
			$form->removeElement ( 'category_id' );
		}
		
		if (! $this->getRequest ()->isPost ()) {
			return;
		}
		
		$values = $this->getRequest ()->getPost ();
		if (! $form->isValid ( $values )) {
			$form->populate ( $values );
			return;
		}
		
		$values = $form->getValues ();
		$values ['slug'] = Engine_Api::_ ()->kowcore ()->strToSlug ( $values ['title'] );
		$values ['creation_date'] = date ( 'Y-m-d H:i:s' );
		$values ['modified_date'] = date ( 'Y-m-d H:i:s' );
		$values ['user_id'] = $viewer->getIdentity ();
		$values ['approved'] = ( int ) (! Engine_Api::_ ()->getApi ( 'settings', 'core' )->getSetting ( 'vote_approval', 0 ));
		$values ['type'] = 'photo';
		
		if (Engine_Api::_ ()->vote ()->checkSlug ( null, $values ['slug'] )) {
			$form->addError ( 'Please provide another title. Voting with this title already exists.' );
			return;
		}
		
		$oldTz = date_default_timezone_get ();
		date_default_timezone_set ( $viewer->timezone );
		
		$start = strtotime ( $values ['starttime'] );
		$end = strtotime ( $values ['endtime'] );
		$now = time ();
		
		if ($start < $now) {
			$form->addError ( 'vote_Start time must be in the future.' );
			return;
		}
		
		if ($end < $now) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		if ($values ['endtime'] < $values ['starttime']) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		date_default_timezone_set ( $oldTz );
		
		$values ['starttime'] = date ( 'Y-m-d H:i:s', $start );
		$values ['endtime'] = date ( 'Y-m-d H:i:s', $end );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$voting = $table->createRow ();
			$voting->setFromArray ( $values );
			$voting->save ();
			
			$raw_tags = preg_split ( '/[,]+/', $values ['tags'] );
			$tags = array ();
			foreach ( $raw_tags as $tag ) {
				$tag = trim ( strip_tags ( $tag ) );
				if ($tag == "") {
					continue;
				}
				$tags [] = $tag;
			}
			
			$voting->tags ()->addTagMaps ( $viewer, $tags );
			$voting->keywords = implode ( ', ', $tags );
			$voting->save ();
			
			if (! empty ( $values ['photo'] )) {
				$voting->setPhoto ( $form->photo );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'member', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			
			$viewMax = array_search ( $values ['auth_view'], $roles );
			$commentMax = array_search ( $values ['auth_comment'], $roles );
			$partMax = array_search ( $values ['auth_participate'], $roles );
			$voteMax = array_search ( $values ['auth_vote'], $roles );
			
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'view', ($i <= $viewMax) );
				$auth->setAllowed ( $voting, $role, 'comment', ($i <= $commentMax) );
				$auth->setAllowed ( $voting, $role, 'participate', ($i <= $partMax) );
				$auth->setAllowed ( $voting, $role, 'vote', ($i <= $voteMax) );
			}
			
			$activityApi = Engine_Api::_ ()->getDbTable ( 'actions', 'activity' );
			$action = $activityApi->addActivity ( $viewer, $voting, 'vote_challenge_new' );
			
			$db->commit ();
			
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		} catch ( Engine_Image_Exception $e ) {
			$db->rollBack ();
			$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'The image you selected was too large.' ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	
	}
	
	public function editAction() {
		if (! $this->_helper->requireUser ()->isValid ())
			return;
		if (! $this->_helper->requireAuth ()->setAuthParams ( 'vote_challenge', null, 'edit' )->isValid ())
			return;
		
		$this->view->navigation = $navigation = Engine_Api::_ ()->getApi ( 'menus', 'core' )->getNavigation ( 'vote_main_photo', array (), 'vote_main_photo_manage' );
		
		$this->view->viewer = $viewer = Engine_Api::_ ()->user ()->getViewer ();
		$this->view->form = $form = new Vote_Form_Edit ();
		$options = Engine_Api::_ ()->vote ()->getCategoryOptions ( 'photo' );
		if (! empty ( $options )) {
			$form->category_id->setMultiOptions ( $options );
		} else {
			$form->removeElement ( 'category_id' );
		}
		
		$challenge_id = $this->_getParam ( 'challenge_id', 0 );
		if (! $challenge_id) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return;
		}
		
		$voting = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' )->find ( $challenge_id )->current ();
		if (! $voting->getIdentity ()) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return;
		}
		
		if ($voting->isStarted ()) {
			$this->_helper->redirector->gotoRoute ( array ('action' => 'index' ), 'vote_general', true );
			return false;
		}
		
		$roles = array ('owner', 'member', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
		if (! $this->getRequest ()->isPost ()) {
			$form->populate ( $voting->toArray () );
			$form->tags->setValue ( $voting->keywords );
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			foreach ( $roles as $role ) {
				if (1 === $auth->isAllowed ( $voting, $role, 'view' )) {
					$form->auth_view->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'comment' )) {
					$form->auth_comment->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'participate' )) {
					$form->auth_participate->setValue ( $role );
				}
				if (1 === $auth->isAllowed ( $voting, $role, 'vote' )) {
					$form->auth_vote->setValue ( $role );
				}
			}
			
			return;
		}
		
		$values = $this->getRequest ()->getPost ();
		if (! $form->isValid ( $values )) {
			$form->populate ( $values );
			return;
		}
		
		$values = $form->getValues ();
		$values ['slug'] = Engine_Api::_ ()->kowcore ()->strToSlug ( $values ['title'] );
		if (Engine_Api::_ ()->vote ()->checkSlug ( $voting, $values ['slug'] )) {
			$form->addError ( 'Please provide another title for competition.' );
			return;
		}
		
		$values ['creation_date'] = date ( 'Y-m-d H:i:s' );
		$values ['modified_date'] = date ( 'Y-m-d H:i:s' );
		
		$oldTz = date_default_timezone_get ();
		date_default_timezone_set ( $viewer->timezone );
		
		$start = strtotime ( $values ['starttime'] );
		$end = strtotime ( $values ['endtime'] );
		$now = time ();
		
		if ($start < $now) {
			$form->addError ( 'vote_Start time must be in the future.' );
			return;
		}
		
		if ($end < $now) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		if ($values ['endtime'] < $values ['starttime']) {
			$form->addError ( 'vote_End time must be in the future.' );
			return;
		}
		
		date_default_timezone_set ( $oldTz );
		
		$values ['starttime'] = date ( 'Y-m-d H:i:s', $start );
		$values ['endtime'] = date ( 'Y-m-d H:i:s', $end );
		
		$table = Engine_Api::_ ()->getDbTable ( 'challenges', 'vote' );
		$db = $table->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$voting->setFromArray ( $values );
			$voting->save ();
			
			$raw_tags = preg_split ( '/[,]+/', $values ['tags'] );
			$tags = array ();
			foreach ( $raw_tags as $tag ) {
				$tag = trim ( strip_tags ( $tag ) );
				if ($tag == "") {
					continue;
				}
				$tags [] = $tag;
			}
			
			$voting->tags ()->addTagMaps ( $viewer, $tags );
			$voting->keywords = implode ( ', ', $tags );
			$voting->save ();
			
			if (! empty ( $values ['photo'] )) {
				$voting->setPhoto ( $form->photo );
			}
			
			$viewMax = array_search ( $values ['auth_view'], $roles );
			$commentMax = array_search ( $values ['auth_comment'], $roles );
			$partMax = array_search ( $values ['auth_participate'], $roles );
			$voteMax = array_search ( $values ['auth_vote'], $roles );
			
			// CREATE AUTH STUFF HERE
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_view']) {
				$auth_view = $values ['auth_view'];
			} else {
				$auth_view = "everyone";
			}
			$viewMax = array_search ( $auth_view, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'view', ($i <= $viewMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_comment']) {
				$auth_comment = $values ['auth_comment'];
			} else {
				$auth_comment = "everyone";
			}
			$commentMax = array_search ( $auth_comment, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'comment', ($i <= $commentMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_participate']) {
				$auth_participate = $values ['auth_participate'];
			} else {
				$auth_participate = "everyone";
			}
			$participateMax = array_search ( $auth_participate, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'participate', ($i <= $participateMax) );
			}
			
			$auth = Engine_Api::_ ()->authorization ()->context;
			$roles = array ('owner', 'owner_member', 'owner_member_member', 'owner_network', 'registered', 'everyone' );
			if ($values ['auth_vote']) {
				$auth_vote = $values ['auth_vote'];
			} else {
				$auth_vote = "everyone";
			}
			$voteMax = array_search ( $auth_vote, $roles );
			foreach ( $roles as $i => $role ) {
				$auth->setAllowed ( $voting, $role, 'vote', ($i <= $voteMax) );
			}
			
			$db->commit ();
			
			return $this->_helper->redirector->gotoRoute ( array ('id' => $voting->getSlug () ), 'vote_profile', true );
		} catch ( Engine_Image_Exception $e ) {
			$db->rollBack ();
			$form->addError ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'The image you selected was too large.' ) );
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
	
	}
	
	public function viewAction() {
		$id = $this->_getParam ( 'pid' );
		if (! $id) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		
		$table = Engine_Api::_ ()->getDbTable ( 'participants', 'vote' );
		$this->view->participant = $participant = $table->find ( $id )->current ();
		if (! $participant) {
			return $this->_helper->redirector->gotoRoute ( array (), 'vote_general', true );
		}
		$this->view->voting = $voting = $participant->getVoting ();
		$this->view->viewer = $viewer = $this->_helper->api ()->user ()->getViewer ();
		
		$this->view->canVote = $voting->isStarted () && $voting->authorization ()->isAllowed ( null, 'vote' );
		
		$this->_helper->requireAuth ()->setNoForward ()->setAuthParams ( $participant, Engine_Api::_ ()->user ()->getViewer (), 'view' );
		
		$tpl = $voting->type . '/view-normal.tpl';
		$format = $this->_getParam ( 'format' );
		
		if ($participant->getIdentity ()) {
			$participant->view_count ++;
			$participant->save ();
		}
		
		if ($format == 'smoothbox') {
			$tpl = $voting->type . '/view-smoothbox.tpl';
		}
		
		$this->view->html = $this->view->render ( $tpl );
	}

}